#include "m_md5.h"

int MDtoStr(unsigned char *MD,char * MDStr)
{
    for (int i = 0; i < 16; i++)
    {
        sprintf(MDStr + i * 2, "%02x", MD[i]);
    }
    return 0;
}
int GenFileMD(char *filePath, unsigned char *MD)
{
    MD5_CTX c;
    MD5_Init(&c);
    int fd = open(filePath, O_RDWR);
    int rlen = 1;
    while (rlen)
    {
        char buf[GENCRPBUF] = {0};
        rlen = read(fd, buf, GENCRPBUF);
        ERROR_CHECK(rlen, -1, "read");
        MD5_Update(&c, buf, rlen);
    }
    MD5_Final(MD, &c);
    return 0;
}
int GenRandStr(char *str, int size)
{
    int i, flag;
    srand(time(NULL));
    for (i = 0; i < size; i++)
    {
        flag = rand() % 3;
        switch (flag)
        {
        case 0:
            str[i] = rand() % 26 + 'a';
            break;
        case 1:
            str[i] = rand() % 26 + 'A';
            break;
        case 2:
            str[i] = rand() % 10 + '0';
            break;
        }
    }
    return 0;
}

int packPassword(char *salt,char * password){
    char bufs[30]={0};
    if(*salt!='$'){
        sprintf(bufs,"$1$%s",salt);
    }else{
        strcpy(bufs,salt);
    }
    char bufp[64]={0};
    strcpy(bufp,password);
    puts(bufs);
    puts(bufp);
    strcpy(password,crypt(bufp,bufs));
    return 0;
}

int takeSalt(char *salt,char * password){
    char * p = password;
    int i=0;
    int c=0;
    while (*(p+i))
    {
        if(*(p+i)=='$'){
            if(c==2){
                strncpy(salt,p,i);
            }
            c++;
        }
        i++;
    }
    
}